﻿using AutoMapper;
using MediatR;
using Return.Enum;
using SlaughterItem.Common.Infrastructures.Interfaces;
using THE_WIND_RISES.Common.Domans.Produce.Craft;
using THE_WIND_RISES.Common.Domans.Produce.Resources;
using THE_WIND_RISES.Common.Domans.Produce.WorkCenter_;
using THE_WIND_RISES.Common.Domans.RBAC;
using THE_WIND_RISES.Common.Dtos;
namespace Production_Set.API.Application.Commands.WorkCenters
{
    /// <summary>
    /// 工作中心添加
    /// </summary>
    public class WorkCenterAddHandler : IRequestHandler<WorkCenterAddCommand, Result>
    {
        private readonly IBaseRepository<WorkCenter> WorkCenterRepository;
        private readonly IBaseRepository<WorkCenterWealth> WorkCenterWealthRepository;
        private readonly IBaseRepository<Resource> ResourceRepository;
        private readonly ILogger<WorkCenterAddHandler> logger;
        private readonly IMapper mapper;

        public WorkCenterAddHandler(IBaseRepository<WorkCenter> workCenterRepository, IMapper mapper, ILogger<WorkCenterAddHandler> logger, IBaseRepository<WorkCenterWealth> workCenterWealthRepository, IBaseRepository<Resource> resourceRepository)
        {
            WorkCenterRepository = workCenterRepository;
            this.mapper = mapper;
            this.logger = logger;
            WorkCenterWealthRepository = workCenterWealthRepository;
            ResourceRepository = resourceRepository;
        }
        /// <summary>
        /// 工作中心添加
        /// </summary>
        public async Task<Result> Handle(WorkCenterAddCommand request, CancellationToken cancellationToken)
        {
            var result = new THE_WIND_RISES.Common.Dtos.Result() { Code = (int)CommonErrorCodes.Added };
            try
            {
                string WorkCenterSql = $"select * from workCenters where WorkCenterName = '{request.WorkCenterName}' or WorkCenterNum ='{request.WorkCenterNum}'";
                var WorkCenterres = WorkCenterRepository.GetAll(WorkCenterSql).FirstOrDefault();
                if (WorkCenterres != null)
                {
                    result.Code = (int)CommonErrorCodes.Added;
                    result.Data = null;
                    result.Msg = "添加工作中心数据失败，请跟换工作中心的名称或者编号,名称或者编号重复";
                    logger.LogError("添加工作中心数据失败，请跟换工作中心的名称或者编号,名称或者编号重复。操作人：" + request.CreateName);
                    foreach (var item in request.WorkCenterWealthData)
                    {
                        var sql = $"select * from workCentersWealth where WorkCenterWealthId = '{item.WorkCenterWealthId}'";
                        var res = WorkCenterWealthRepository.GetAll(sql);
                        if (res.Count() > 0)
                        {
                            
                        }
                        else
                        {
                            var WorkCenterWealthSql1 = "insert into workCentersWealth values(@WorkCenterWealthId,@WorkCenterWealthNum,@WorkCenterWealthName,@UsableNum,@Abstract,@WorkCenterWealthState,@CreateTime,@CreateName,@IsDelWorkCenterWealth,@WorkCenterId);";
                            string WorkCenterSql2 = $"select * from workCenters where WorkCenterId = {WorkCenterres.WorkCenterId}";
                            WorkCenterres = WorkCenterRepository.GetAll(WorkCenterSql2).FirstOrDefault();

                            string ResourceSql = $"select * from Resource where ResourceId = {item.WorkCenterWealthId}";
                            var ResourceRes = ResourceRepository.GetAll(ResourceSql).FirstOrDefault();

                            var AddResa = WorkCenterWealthRepository.Add(WorkCenterWealthSql1, new
                            {
                                WorkCenterWealthId = 0,
                                WorkCenterWealthNum = ResourceRes.ResourceNo,
                                WorkCenterWealthName = ResourceRes.ResourceName,
                                UsableNum = item.UsableNum,
                                Abstract = item.Abstract,
                                WorkCenterWealthState = item.WorkCenterWealthState,
                                CreateTime = item.CreateTime,
                                CreateName = item.CreateName,
                                IsDelWorkCenterWealth = item.IsDelWorkCenterWealth,
                                WorkCenterId = WorkCenterres.WorkCenterId
                            });
                        }
                    }
                    return result;
                }
                else
                {
                    var AddData = mapper.Map<WorkCenter>(request);
                    WorkCenterSql = "insert into workCenters values(@WorkCenterId,@WorkCenterNum,@WorkCenterName,@WorkCenterType,@ClassesData,@CreateTime,@CreateName,@WorkCenterState,@ApprovalState,@IsDelWorkCenter);";
                    var AddRes = WorkCenterRepository.Add(WorkCenterSql, AddData);
                    if (AddRes > 0)
                    {
                        string WorkCenterSql1 = $"select * from workCenters where WorkCenterName = '{request.WorkCenterName}' or WorkCenterNum ='{request.WorkCenterNum}'";
                        WorkCenterres = WorkCenterRepository.GetAll(WorkCenterSql1).FirstOrDefault();
                        var data = new
                        {
                            WorkCenterId = WorkCenterres.WorkCenterId
                        };
                        foreach (var item in request.WorkCenterWealthData)
                        {
                            var WorkCenterWealthSql1 = "insert into workCentersWealth values(@WorkCenterWealthId,@WorkCenterWealthNum,@WorkCenterWealthName,@UsableNum,@Abstract,@WorkCenterWealthState,@CreateTime,@CreateName,@IsDelWorkCenterWealth,@WorkCenterId);";
                            string WorkCenterSql2 = $"select * from workCenters where WorkCenterId = {WorkCenterres.WorkCenterId}";
                            WorkCenterres = WorkCenterRepository.GetAll(WorkCenterSql2).FirstOrDefault();
                            string ResourceSql = $"select * from Resource where ResourceId = {item.WorkCenterWealthId}";
                            var ResourceRes = ResourceRepository.GetAll(ResourceSql).FirstOrDefault();
                            var AddResa = WorkCenterWealthRepository.Add(WorkCenterWealthSql1, new
                            {
                                WorkCenterWealthId = 0,
                                WorkCenterWealthNum = ResourceRes.ResourceNo,
                                WorkCenterWealthName = ResourceRes.ResourceName,
                                UsableNum = item.UsableNum,
                                Abstract = item.Abstract,
                                WorkCenterWealthState = item.WorkCenterWealthState,
                                CreateTime = item.CreateTime,
                                CreateName = item.CreateName,
                                IsDelWorkCenterWealth = item.IsDelWorkCenterWealth,
                                WorkCenterId = WorkCenterres.WorkCenterId
                            });
                        }
                        result.Code = (int)CommonErrorCodes.Success;
                        result.Data = null;
                        result.Msg = "添加工作中心成功";
                        logger.LogInformation("添加工作中心成功。操作人：" + request.CreateName);
                        return result;
                    }
                }
            }
            catch (Exception ex)
            {
                logger.LogError($"添加工作中心失败," + ex.Message);
                throw;
            }
            return result;
        }
    }
}
